package com.example.qiandao.service;

import com.example.qiandao.controller.responsedto.ClassDTO;
import com.example.qiandao.controller.responsedto.CourseDTO;
import com.example.qiandao.entity.Clazz;
import com.example.qiandao.entity.Course;
import com.example.qiandao.repository.ClazzRepository;
import com.example.qiandao.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CourseService {
    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private ClazzRepository clazzRepository;

    public List<CourseDTO> getCoursesByTeacherId(Long teacherId) {

        return courseRepository.findCoursesByTeacherId(teacherId).stream()
                .map(course -> new CourseDTO(course.getId(), course.getCourseName()))
                .collect(Collectors.toList());

    }

    public List<CourseDTO> getCoursesByStudentId(Long studentId) {
        return clazzRepository.findClassesByStudentId(studentId).stream()
                .map(clazz -> new CourseDTO(clazz.getCourse().getId(), clazz.getCourse().getCourseName()))
                .collect(Collectors.toList());
    }

    public boolean addCourse(Course course) {
        Course newCourse = courseRepository.save(course);
        if (newCourse != null)
            return true;
        else
            return false;
    }


    public Course getCourseById(Long id) {
        return courseRepository.findById(id).orElse(null);
    }

    public boolean updateCourse(Course course) {
        if (courseRepository.existsById(course.getId())) {
            courseRepository.save(course);
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteCourse(Long id) {
        if (courseRepository.existsById(id)) {
            courseRepository.deleteById(id);
            return true;
        } else {
            return false;
        }
    }
}